package com.fzrskj.cloud.free.user.utils;

import com.fzrskj.cloud.free.core.AppStatus;
import com.fzrskj.cloud.free.core.enums.MessageSendWayEnum;
import com.fzrskj.cloud.free.core.opitimize.session.SessionCoreUtils;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.sys.utils.SendMailUtils;
import com.fzrskj.cloud.free.sys.utils.SendSMSUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * UserPersonalUtils.
 *
 * @author zj.
 *         Created on 2019/2/25 0025.
 */
public class UserPersonalUtils extends CObject {
    private final Integer timeout = 600;
    private final String MAIL_OLD = "userPersonalEditMail";
    private final String SMS_OLD = "userPersonalEditSms";
    private final String editMobileOldBizCode = "modifyMobile";
    private final String editMobileBizCode = "newMobile";
    private final String editMailOldBizCode = "modifyMail";
    private final String editMailBizCode = "newMail";

    /**
     * 发送个人信息修改验证码.
     * @param userId 用户ID.
     * @param way 发送方式.
     * @param bizCode 业务编码.
     * @return Boolean.
     */
    public Boolean sendOldCheckCode(Integer userId, String way, String bizCode) {
        //获取用户信息
        UserAccountView view = UserAccountUtils.getUserAccountView(userId);
        if (null == view) {
            this.setErrCode("USER NOT FOUND", "用户信息不存在！");
            return false;
        }

        //生成验证码
        String sessionKey = bizCode + ":" + userId.toString();
        String code = SessionCoreUtils.get(sessionKey);
        if (StrTool.isBlankStr(code)) {
            code = CStrTool.randNum(6);
        }
        SessionCoreUtils.set(sessionKey, code, this.timeout);

        List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
        messageParams.add(new BasicNameValuePair("\\[验证码\\]", code));

        //发送
        if (MessageSendWayEnum.MOBILE.equals(way)) {
            //手机短信
            if (StrTool.isBlankStr(view.getMobile())) {
                this.setErrCode("USER MOBILE ERROR", "手机号未设置！");
                return false;
            }

            Map<String,Object> map = new HashedMap();
            map.put("userId", view.getUserId());
            map.put("mobile", view.getMobile());

            SendSMSUtils smsUtils = new SendSMSUtils();
            smsUtils.loadWebsiteParam(messageParams);
            smsUtils.sendSMS(this.SMS_OLD, map, messageParams);
            return true;
        } else {
            //邮箱发送
            if (StrTool.isBlankStr(view.getEmail())) {
                this.setErrCode("USER EMAIL ERROR", "邮箱未设置！");
                return false;
            }

            SendMailUtils mailUtils = new SendMailUtils();
            mailUtils.loadWebsiteParam(messageParams);
            mailUtils.sendMail(this.MAIL_OLD, view.getEmail(), messageParams);
            return true;
        }
    }

    /**
     * 发送新手机号验证码.
     * @param userId 用户ID.
     * @param mobile 手机号.
     * @return Boolean.
     */
    public Boolean sendMobileCheckCode(Integer userId, String mobile) {
        //获取用户信息
        UserAccountView view = UserAccountUtils.getUserAccountView(userId);
        if (null == view) {
            this.setErrCode("USER NOT FOUND", "用户信息不存在！");
            return false;
        }

        //手机是否被其他用户占用
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccountView exist = accountUtils.isRegisterMobile(mobile, userId);
        if (null != exist) {
            this.setErrCode("MOBILE EXISTED", "手机号已被其他用户使用！");
            return false;
        }

        //生成验证码
        String sessionKey = this.editMobileBizCode + ":" + userId.toString();
        Map<String, String> codeInfo = SessionCoreUtils.get(sessionKey);
        if (null == codeInfo) {
            String code = CStrTool.randNum(6);
            codeInfo = new HashedMap();
            codeInfo.put("code", code);
            codeInfo.put("mobile", mobile);
        }
        SessionCoreUtils.set(sessionKey, codeInfo, this.timeout);

        List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
        messageParams.add(new BasicNameValuePair("\\[验证码\\]", codeInfo.get("code")));

        //发送
        Map<String,Object> map = new HashedMap();
        map.put("userId", view.getUserId());
        map.put("mobile", mobile);

        SendSMSUtils smsUtils = new SendSMSUtils();
        smsUtils.loadWebsiteParam(messageParams);
        smsUtils.sendSMS(this.SMS_OLD, map, messageParams);
        return true;
    }

    /**
     * 修改用户手机号.
     * @param userId 用户ID.
     * @param mobile 手机号.
     * @param oldCheckCode 旧校验码.
     * @param newCheckCode 新校验码.
     * @return Boolean.
     */
    public Boolean modifyUserMobile(Integer userId, String mobile, String oldCheckCode, String newCheckCode) {
        String oldSessionKey = this.editMobileOldBizCode + ":" + userId.toString();
        String oldSessionCode = SessionCoreUtils.get(oldSessionKey);
        if (AppStatus.getDebug()) {
            oldSessionCode = "888888";
        }
        if (StrTool.isBlankStr(oldSessionCode) || !oldSessionCode.equals(oldCheckCode)) {
            this.setErrCode("SAFE CODE ERROR", "安全码校验失败");
            return false;
        }

        String newSessionKey = this.editMobileBizCode + ":" + userId.toString();
        Map<String, String> codeInfo = SessionCoreUtils.get(newSessionKey);
        if (null == codeInfo) {
            this.setErrCode("CHECK CODE ERROR", "新号码验证码校验失败");
            return false;
        }
        String newSessionCode = codeInfo.get("code");
        String newMobile = codeInfo.get("mobile");
        if (AppStatus.getDebug()) {
            newSessionCode = "888888";
        }
        if (StrTool.isBlankStr(newSessionCode) || !newSessionCode.equals(newCheckCode) || !newMobile.equals(mobile)) {
            this.setErrCode("CHECK CODE ERROR", "新号码验证码校验失败");
            return false;
        }

        //获取用户信息
        UserAccountView view = UserAccountUtils.getUserAccountView(userId);
        if (null == view) {
            this.setErrCode("USER NOT FOUND", "用户信息不存在！");
            return false;
        }

        //手机是否被其他用户占用
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccountView exist = accountUtils.isRegisterMobile(mobile, userId);
        if (null != exist) {
            this.setErrCode("MOBILE EXISTED", "手机号已被其他用户使用！");
            return false;
        }

        //修改
        Map<String, Object> update = new HashedMap();
        update.put("mobile", mobile);
        Map<String, Object> where = new HashedMap();
        where.put("userId", userId);
        UserAccountDataUtils dataUtils = new UserAccountDataUtils();
        Integer affect = dataUtils.modifyAccountData(update, where);
        if (affect < 1) {
            this.setErrCode(dataUtils.getErrCode(), dataUtils.getMsg());
            return false;
        }
        return true;
    }

    /**
     * 发送新邮箱验证码.
     * @param userId 用户ID.
     * @param mail 邮箱.
     * @return Boolean.
     */
    public Boolean sendMailCheckCode(Integer userId, String mail) {
        //获取用户信息
        UserAccountView view = UserAccountUtils.getUserAccountView(userId);
        if (null == view) {
            this.setErrCode("USER NOT FOUND", "用户信息不存在！");
            return false;
        }

        //邮箱是否被其他用户占用
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccountView exist = accountUtils.isRegisterEmail(mail, userId);
        if (null != exist) {
            this.setErrCode("MOBILE EXISTED", "该邮箱已被其他用户使用！");
            return false;
        }

        //生成验证码
        String sessionKey = this.editMailBizCode + ":" + userId.toString();
        Map<String, String> codeInfo = SessionCoreUtils.get(sessionKey);
        if (null == codeInfo) {
            String code = CStrTool.randNum(6);
            codeInfo = new HashedMap();
            codeInfo.put("code", code);
            codeInfo.put("mail", mail);
        }
        SessionCoreUtils.set(sessionKey, codeInfo, this.timeout);

        List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
        messageParams.add(new BasicNameValuePair("\\[验证码\\]", codeInfo.get("code")));

        //发送
        SendMailUtils mailUtils = new SendMailUtils();
        mailUtils.loadWebsiteParam(messageParams);
        mailUtils.sendMail(this.MAIL_OLD, mail, messageParams);
        return true;
    }

    /**
     * 修改用户邮箱.
     * @param userId 用户ID.
     * @param mail 新邮箱.
     * @param oldCheckCode 安全校验码.
     * @param newCheckCode 邮箱校验码.
     * @return Boolean.
     */
    public Boolean modifyUserMail(Integer userId, String mail, String oldCheckCode, String newCheckCode) {
        String oldSessionKey = this.editMailOldBizCode + ":" + userId.toString();
        String oldSessionCode = SessionCoreUtils.get(oldSessionKey);
        if (StrTool.isBlankStr(oldSessionCode) || !oldSessionCode.equals(oldCheckCode)) {
            this.setErrCode("SAFE CODE ERROR", "安全码校验失败");
            return false;
        }

        String newSessionKey = this.editMailBizCode + ":" + userId.toString();
        Map<String, String> codeInfo = SessionCoreUtils.get(newSessionKey);
        if (null == codeInfo) {
            this.setErrCode("CHECK CODE ERROR", "新邮箱验证码校验失败");
            return false;
        }
        String newSessionCode = codeInfo.get("code");
        String newMail = codeInfo.get("mail");
        if (StrTool.isBlankStr(newSessionCode) || !newSessionCode.equals(newCheckCode) || !newMail.equals(mail)) {
            this.setErrCode("CHECK CODE ERROR", "新邮箱验证码校验失败");
            return false;
        }

        //获取用户信息
        UserAccountView view = UserAccountUtils.getUserAccountView(userId);
        if (null == view) {
            this.setErrCode("USER NOT FOUND", "用户信息不存在！");
            return false;
        }

        //邮箱是否被其他用户占用
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccountView exist = accountUtils.isRegisterEmail(mail, userId);
        if (null != exist) {
            this.setErrCode("MOBILE EXISTED", "该邮箱已被其他用户使用！");
            return false;
        }

        //修改
        Map<String, Object> update = new HashedMap();
        update.put("email", mail);
        Map<String, Object> where = new HashedMap();
        where.put("userId", userId);
        UserAccountDataUtils dataUtils = new UserAccountDataUtils();
        Integer affect = dataUtils.modifyAccountData(update, where);
        if (affect < 1) {
            this.setErrCode(dataUtils.getErrCode(), dataUtils.getMsg());
            return false;
        }
        return true;
    }
}

